package com.admin.kotlintest.utils

import android.content.Context
import android.util.Log
import com.google.gson.*
import org.json.JSONObject
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStreamReader


/**
 * Created by 吴昶 on 2018/4/18.
 */
class GsonUtils{

    companion object {

        fun <T> paresJsonWithGon(string: String,t :Class<T>):T{
            val gson=Gson()
            return gson.fromJson<T>(string,t)
        }
        //从assets中获取json数据
        fun getJson(context: Context, fileName: String): String {
            val stringBuilder = StringBuilder()
            //获得assets资源管理器
            val assetManager = context.getAssets()
            //使用IO流读取json文件内容
            try {
                val bufferedReader = BufferedReader(InputStreamReader(
                        assetManager.open(fileName), "utf-8"))
                var lines=bufferedReader.readLines()
                for (i in lines.indices){
                    stringBuilder.append(lines[i])
                }
            } catch (e: IOException) {
                e.printStackTrace()
            }

            return stringBuilder.toString()
        }


        fun <T> paresJsonArray(string: String,t :Class<T>):ArrayList<T>{
            Log.e("===",string)
            val parser=JSONObject(string)
            val typs=parser.getJSONArray("types")
            val gson=Gson()
            val list=ArrayList<T>()
            for (i in 0 until typs.length()) {
                //使用GSON，直接转成Bean对象
                val userBean = gson.fromJson(typs.getJSONObject(i).toString(), t)
                list.add(userBean)
            }
            return list
        }











    }



}